<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>初识JavaScript Promises之一 | 在路上</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="JavaScript有很多槽点，嵌套回调怕是千夫所指。 很久之前，我一直使用async来处理JavaScript异步编程中的嵌套回调问题。当然我也大概的了解过一些其它旨在解决这些问题的类库，诸如EventProxy、Jscex、StepJS、thenjs。 当我第一次看到Promises规范的时候，我根本无法理解它所带来的好处。譬如每个初次学习Promises的人都见过如下的示例代码：123456">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="初识JavaScript Promises之一">
<meta property="og:url" content="http://yoursite.com/2014/06/28/初识JavaScript Promises之一/index.html">
<meta property="og:site_name" content="在路上">
<meta property="og:description" content="JavaScript有很多槽点，嵌套回调怕是千夫所指。 很久之前，我一直使用async来处理JavaScript异步编程中的嵌套回调问题。当然我也大概的了解过一些其它旨在解决这些问题的类库，诸如EventProxy、Jscex、StepJS、thenjs。 当我第一次看到Promises规范的时候，我根本无法理解它所带来的好处。譬如每个初次学习Promises的人都见过如下的示例代码：123456">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-03-26T11:35:06.704Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="初识JavaScript Promises之一">
<meta name="twitter:description" content="JavaScript有很多槽点，嵌套回调怕是千夫所指。 很久之前，我一直使用async来处理JavaScript异步编程中的嵌套回调问题。当然我也大概的了解过一些其它旨在解决这些问题的类库，诸如EventProxy、Jscex、StepJS、thenjs。 当我第一次看到Promises规范的时候，我根本无法理解它所带来的好处。譬如每个初次学习Promises的人都见过如下的示例代码：123456">
  
    <link rel="alternate" href="/atom.xml" title="在路上" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">在路上</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">一位崇尚价值投资的 Web 开发者</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-初识JavaScript Promises之一" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2014/06/28/初识JavaScript Promises之一/" class="article-date">
  <time datetime="2014-06-27T16:00:00.000Z" itemprop="datePublished">2014-06-28</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      初识JavaScript Promises之一
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>JavaScript有很多槽点，嵌套回调怕是千夫所指。</p>
<p>很久之前，我一直使用async来处理JavaScript异步编程中的嵌套回调问题。当然我也大概的了解过一些其它旨在解决这些问题的类库，诸如EventProxy、Jscex、StepJS、thenjs。</p>
<p>当我第一次看到Promises规范的时候，我根本无法理解它所带来的好处。譬如每个初次学习Promises的人都见过如下的示例代码：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//callbacks</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callback</span>(<span class="params">err, value</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(err)&#123;</span><br><span class="line">		<span class="comment">// do something</span></span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//do other things with value</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//Promises</span></span><br><span class="line">promise.then(<span class="function"><span class="keyword">function</span>(<span class="params">value</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//do something with value</span></span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//do other things with error</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>很难相信上面的代码会让人对Promises刮目相看。不过正如<a href="https://github.com/petkaantonov/bluebird" target="_blank" rel="noopener">bluebird</a>作者Petka所说，上面的代码是<br><a href="https://twitter.com/PetkaAntonov/status/475274392461910016" target="_blank" rel="noopener">“最不诚实的比较”</a>。所以我恳请你把类似的代码从你的记忆中擦出吧。</p>
<p>不妨让我们再回到async的讨论上。async的问题在于它不能优雅地应对需求的变化，一旦业务逻辑有较大的变化，代码结构会进行大幅度的调整，而Promises却能够轻松的应对这种变化。待时机适宜我会进行详细的比较，首先让我们开始快速地了解Promises。</p>
<hr>
<h2 id="Promises是什么"><a href="#Promises是什么" class="headerlink" title="Promises是什么"></a>Promises是什么</h2><p>Promises象征着一个异步操作的最终结果。Promises交互主要通过它的then方法，then方法接受一个回调函数，这个回调函数接受执行成功的返回值或执行失败的错误原因，错误原因一般是Error对象。<strong>需要注意的是，then方法执行的返回值是一个Promise对象，而then方法接受的回调函数的返回值则可以是任意的JavaScript对象，包括Promises。基于这种机制，Promise对象的链式调用就起作用了。</strong></p>
<h2 id="Promises的状态"><a href="#Promises的状态" class="headerlink" title="Promises的状态"></a>Promises的状态</h2><p>Promise对象有三种状态：pending（初始状态）、fulfilled（成功执行）、rejected（执行出错）。pending状态的Promise对象可以转换到其它两种状态。</p>
<hr>
<p> 上面的文本不够形象，不妨上些代码来加深对Promises的认识。</p>
<p>注：由于主流的JavaScript环境（包括NodeJS）对Promises/A+标准的实现差强人意，我的示例均使用了第三方类库<a href="https://github.com/petkaantonov/bluebird" target="_blank" rel="noopener">bluebird</a>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>)</span><br><span class="line"><span class="keyword">var</span> <span class="built_in">Promise</span> = <span class="built_in">require</span>(<span class="string">'bluebird'</span>)</span><br><span class="line"><span class="comment">//改造fs.readFile为Promise版本</span></span><br><span class="line"><span class="keyword">var</span> readFileAsync = <span class="function"><span class="keyword">function</span>(<span class="params">path</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//返回一个Promise对象，初始状态pending</span></span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">fulfill, reject</span>)</span>&#123;</span><br><span class="line">		fs.readFile(path,  <span class="string">'utf8'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, content</span>)</span>&#123;</span><br><span class="line">			<span class="comment">//由pending状态进入rejected状态</span></span><br><span class="line">			<span class="keyword">if</span>(err)<span class="keyword">return</span> reject(err)</span><br><span class="line">			<span class="comment">//由pending状态进入fulfilled状态</span></span><br><span class="line">			<span class="keyword">return</span> fulfill(content)</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//开始使用，调用其then方法，回调接受执行成功的返回值</span></span><br><span class="line">readFileAsync(<span class="string">'./promise-1.js'</span>).then(<span class="function"><span class="keyword">function</span>(<span class="params">content</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(content)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>看了上面的代码以后，是不是觉得Promises其实并不复杂呢。</p>
<p>OK，我们继续延续上面的代码，来简单比较一下传统回调和Promises的使用上的差别：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">* 简单比较一下传统方式和Promises方式</span></span><br><span class="line"><span class="comment">* 需求：读取两个文件并打印内容</span></span><br><span class="line"><span class="comment">* */</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">//callbacks</span></span><br><span class="line">fs.readFile(<span class="string">'./promise-1.js'</span>, <span class="string">'utf8'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, content1</span>)</span>&#123;</span><br><span class="line">	<span class="comment">//嵌套一次</span></span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">'#'</span>, content1)</span><br><span class="line">	fs.readFile(<span class="string">'./promise-1.js'</span>, <span class="string">'utf8'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, content2</span>)</span>&#123;</span><br><span class="line"> 		<span class="comment">//第二次嵌套</span></span><br><span class="line">		<span class="built_in">console</span>.log(<span class="string">'##'</span>, content2)</span><br><span class="line">	&#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//Promises</span></span><br><span class="line">readFileAsync(<span class="string">'./promise-1.js'</span>).then(<span class="function"><span class="keyword">function</span>(<span class="params">content1</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">'#'</span>, content1)</span><br><span class="line">	<span class="comment">//这里返回一个Promise对象</span></span><br><span class="line">	<span class="keyword">return</span> readFileAsync(<span class="string">'./promiscuitye-1.js'</span>)</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">content2</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">'##'</span>, content2)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>上面的代码都没有错误处理，这是一个后果很严重的坏习惯。不过今天我们的重点不在这里，而是分析上下两段代码的主要区别。</p>
<p>第一段代码是传统的嵌套回调，在第二次打印的时候已经使用了两次缩进，而Promises链式调用then方法成功地避免了一次缩进（嵌套），维持了代码结构的相对平坦。上面的代码略显简陋，如果再加上错误处理，Promises毫无疑问将会大放光彩，有兴趣请关注后续章节。</p>
<p>本章写到这里就结束了，相信大家已经对Promises的有了一个初步认识。规范文档往往很难理解，我没有过多的描述规范，因为我相信代码最能够解释一切。不过对规范文档有兴趣的可以自行阅读参考链接。</p>
<p>最后我想强调的一点就是：<strong>Promises这种维持代码结构平坦的魔力在业务逻辑复杂多变的情况下是非常有用的</strong>。</p>
<h2 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h2><blockquote>
<ul>
<li><a href="https://github.com/promises-aplus/promises-spec" target="_blank" rel="noopener">Promises/A+ 标准</a></li>
<li><a href="https://github.com/petkaantonov/bluebird" target="_blank" rel="noopener">Bluebird</a></li>
</ul>
</blockquote>
<hr>
<p>未完待续(2014-06-28 00:59)</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2014/06/28/初识JavaScript Promises之一/" data-id="cjf865ug0001j8wp1iubqx36w" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/">JavaScript</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2014/07/15/初识JavaScript Promises之二/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          初识JavaScript Promises之二
        
      </div>
    </a>
  
  
    <a href="/2012/11/11/Ajax-Encoding/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Ajax编码问题</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/">JavaScript</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript-解析器/">JavaScript,解析器</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React/">React</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Redux/">Redux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SlimerJS/">SlimerJS</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/代码管理/">代码管理</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/持续集成/">持续集成</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签云</h3>
    <div class="widget tagcloud">
      <a href="/tags/JavaScript/" style="font-size: 20px;">JavaScript</a> <a href="/tags/JavaScript-解析器/" style="font-size: 10px;">JavaScript,解析器</a> <a href="/tags/React/" style="font-size: 16.67px;">React</a> <a href="/tags/Redux/" style="font-size: 10px;">Redux</a> <a href="/tags/SlimerJS/" style="font-size: 10px;">SlimerJS</a> <a href="/tags/代码管理/" style="font-size: 10px;">代码管理</a> <a href="/tags/持续集成/" style="font-size: 13.33px;">持续集成</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/09/">九月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/07/">七月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/06/">六月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/03/">三月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/02/">二月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">十二月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/06/">六月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">五月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">四月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">七月 2014</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">六月 2014</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/11/">十一月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/10/">十月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/07/">七月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">三月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/02/">二月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2011/10/">十月 2011</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2010/01/">一月 2010</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/1970/01/">一月 1970</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/09/09/space/">空格</a>
          </li>
        
          <li>
            <a href="/2016/07/17/parser/">JavaScript Parser资源总结</a>
          </li>
        
          <li>
            <a href="/2016/06/29/slimerjs/">使用SlimerJS将网页输出为PDF</a>
          </li>
        
          <li>
            <a href="/2016/06/26/code-management/">代码管理</a>
          </li>
        
          <li>
            <a href="/2016/06/18/violet/">violet - 值得一试的写作同步小助手</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 Simon Xu<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



  </div>
</body>
</html>